package SwordFingerOffer;

public class Q58_1_ReverseString {
    //翻转单词顺序
    //利用尾指针 + 记忆指针 + " " ==> 重点在于区分首段字符串与中间段字符串的处理
    public String reverseWords(String s) {

        if (s == null || s.length() == 0){
            return "";
        }
        s = s.trim();
        StringBuilder sb = new StringBuilder();
        char[] str = s.toCharArray();
        //辅助指针
        int p = str.length - 1;
        for (int i = str.length - 1; i >= 0 ; i--) {
            //i == 0 是对头节点的处理
            if (str[i] == ' ' || i == 0){
                for (int j = str[i] == ' ' ? i + 1 : i; j <= p; j++) {
                    sb.append(str[j]);
                }
                if (i != 0){
                    sb.append(' ');
                }else {
                    return sb.toString();
                }

                //消除重复空格
                while (str[i] == ' '){
                    i--;
                }
                //重置 p
                //这里主要是抵消循环 i--的问题
                p = i++;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Q58_1_ReverseString fun = new Q58_1_ReverseString();
        System.out.println(fun.reverseWords("the sky"));
    }
}
